<?php

/**
 * @Author: wuchenge
 * @Date: 2020-11-30 14:15:20
 */

namespace App\Http\Controllers;

use App\Models\Message;
use Illuminate\Http\Request;
use Response;

class ApiController extends Controller
{
    protected $error_code  = 0;
    protected $message     = 'success';
    protected $failed_code = 1;

    /**
     * [getErrorCode 获取消息码]
     * @return [type] [description]
     */
    public function getErrorCode()
    {
        return $this->error_code;
    }

    /**
     * [getErrorCode 获取消息]
     * @return [type] [description]
     */
    public function getMessage()
    {

        return $this->message;
    }

    /**
     * [setErrorCode 设置消息码 ]
     * @param [type] $status_code [消息码]
     */
    public function setErrorCode($error_code, $message = '')
    {
        $this->error_code = $error_code;
        if ($message) {
            $this->message = $message;
        }

        return $this;
    }

    /**
     * 获取language 默认中文
     */
    public function getLanguage()
    {
        // header("app-language:en");
        if (array_key_exists('HTTP_APP_LANGUAGE', $_SERVER)) {
            return $_SERVER['HTTP_APP_LANGUAGE'];
        }

        if (array_key_exists('language', $_POST)) {
            return $_POST['language'];
        }

        if (array_key_exists('language', $_GET)) {
            return $_GET['language'];
        }

        return config('api.common.default_language');
    }

    /**
     * [response 返回JSON格式数据并添加消息码和消息]
     * @param  [type] $data [description]
     * @return [type]       [description]
     */
    public function response($data = [], $message = '')
    {
        // 返回总数据
        $response = [];

        // 返回消息码和消息
        $error_code = $this->getErrorCode();

        if (!empty($message)) {
            $message = $message;
        } else {
            // 获取语言
            $language = $this->getLanguage();
            $message  = Message::getMessage($error_code, $language);
        }

        // 空数组返回空对象
        if (empty($data)) {
            // $data = (object) $data;
            $data = null;
        }

        $response['data']       = $data;
        $response['message']    = $message;
        $response['error_code'] = $error_code;

        return Response::json($response);
    }

    /**
     * 失败返回
     * @param  integer $code    [description]
     * @param  string  $message [description]
     * @return [type]           [description]
     */
    public function failed($code = 1, $message = '')
    {
        return $this->setErrorCode($code, $message)->response();
    }
}
